package com.hiup.utils;

import com.hiup.vo.ImageVo;
import net.sf.json.JSONObject;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Objects;

/**
 * @author cyf
 * @description
 * @create 2018-07-24 13:42
 **/
public class JSONUtil {
    private static final Logger log = LoggerFactory.getLogger(JSONUtil.class);

    private static ObjectMapper OBJECT_MAPPER = new ObjectMapper();


    /**
     * 对象转为json
     * 异常Unrecognized field, not marked as ignorable,
     * 在实体类上添加 org.codehaus.jackson.annotate.JsonProperty @JsonProperty(value = "AE")
     *
     * @param data
     * @return
     */
    public static String objectToJson(Object data) {
        if(Objects.isNull(data)){
            return null;
        }
        try {
            String result = OBJECT_MAPPER.writeValueAsString(data);
            return result;
        } catch (IOException e) {
            log.error("objectToJson error!!!");
            log.error("异常原因是: {},{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * json 转为 对象
     *
     * @param jsonData
     * @param beanType
     * @param <T>
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = OBJECT_MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (IOException e) {
            log.error("jsonToPojo error!!!");
            log.error("异常原因是: {},{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获取json的属性的值,没有则为空
     *
     * @param key
     * @param data
     * @return
     */
    public static String getValue(String key, JSONObject data) {
        String value = "";
        if (data.has(key)) {
            return data.get(key).toString();
        }
        return value;
    }


    public static void main(String[] args) {
        String image = "{\"studyList\":[{\"patientID\":\"影像号\",\"accNum\":\"存取编号\",\"studyUid\":\"检查号\",\"AE\":\"前置机AETitle\",\"IP\":\"前置机IP\",\"port\":\"关联ID\",\"examType\":\"检查类型\",\"examBodyPart\":\"检查部位\",\"examMethod\":\"检查方法\"}],\"resultCode\":\"0成功,1失败\",\"errorMsg\":\"错误信息，成功无内容\"}";
        ImageVo imageVo = JSONUtil.jsonToPojo(image, ImageVo.class);
        Assert.assertNotNull(imageVo);
        log.info("转换后结果: {}", imageVo);
    }

}
